#-*-coding:utf-8-*-
#!/usr/bin/python

from lib import config, req_sy, db_sy
from lib import email_sy as email
from lib.logger import logger
from bs4 import BeautifulSoup
import time
import re
import gevent.monkey
gevent.monkey.patch_socket()
import gevent
from gevent.pool import Pool

onlive_src = 'quanmin'
gpool = Pool(config.GPOOLSIZE)

# 处理来源于全民的直播视频，直播地址： http://www.quanmin.tv/v/35743
def _pro_onlivedata_from_quanmin(room_id):
	return 'http://www.quanmin.tv/swf/player.swf?skinUrl=/swf/skin.swf&type=live&playMode=Http_FLV_Live&isIndex=0&roomId='+ str(room_id)+'&iplayStatus=1&videoQuality=234'

def get_data_action(is_get_livedata = True):
	# 全民视频列表页api:http://www.quanmin.tv/json/play/list.json
	# 在线人数作为是否继续爬取的判断条件
	res_data = []
	game_type = config.QUANMIN_GAME
	quanmin_api = config.QUANMIN_API
	response = req_sy.get_html(quanmin_api, is_json=True)
	if response and len(response['data']) != 0:
		res_list=response['data']
		for zb in res_list:
			kw = {}				
			views = int(zb['view'])
			categor = zb['category_slug']
			if categor not in game_type:
				continue
			kw['views'] = views
			kw['zbid'] = zb['uid']
			room_id = zb['uid']
			kw['livedata'] = _pro_onlivedata_from_quanmin(room_id)
			kw['zbname'] = zb['nick']
			kw['source'] = onlive_src
			kw['views'] = views
			kw['title'] = zb['title']
			kw['category'] = game_type[categor]
			kw['inputtime'] = int(time.time())
			kw['zb_thumb'] = zb['avatar']
			kw['thumb'] = zb['thumb']
				
			res_data.append(kw)
	else:
		logger.error("%s | %s" % ("get "+onlive_src+" API Failed", quanmin_api))
		email.send_email(onlive_src+u'直播API获取失败', "%s | %s" % ("get QUANMIN API Failed", quanmin_api))
		top_views = 100

	return res_data

if __name__ == "__main__":
	now =  time.time()
	dbconn = db_sy.getConnection()
	update_data = get_data_action(is_get_livedata = True)
	db_sy.db_insert(dbconn, update_data)
	dbconn.close()
	print "time cost : " + str(int((time.time() - now))) + " seconds"